package cn.i5.remoteinvocationcontrol.core;

import cn.i5.remoteinvocationcontrol.annotation.RemoteInvocationControl;
import cn.i5.remoteinvocationcontrol.config.RemoteInvocationControlConfig;
import cn.i5.remoteinvocationcontrol.constant.ServicesName;
import cn.i5.remoteinvocationcontrol.utils.CommonUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务名IP校验者
 *
 * @author mc0710
 */
public class ServicesNameChecker {

    /**
     * 校验
     */
    public void check(RemoteInvocationControl remoteInvocationControl, RemoteInvocationControlConfig remoteInvocationControlConfig) {
        // 得到服务器名
        ServicesName[] servicesName = remoteInvocationControl.servicesName();
        List<String> ipList = new ArrayList<>();
        for (ServicesName name : servicesName) {
            // 得到name对应的IP列表
            List<String> nameIpList = remoteInvocationControlConfig.getServicesNameMap().get(name);
            ipList.addAll(nameIpList);
        }
        if (!CollectionUtils.isEmpty(ipList)) {
            checkServicesNameIp(ipList);
        }
    }

    /**
     * 服务名对应IP校验
     *
     * @param ipList
     */
    private void checkServicesNameIp(List<String> ipList) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = CommonUtils.getIp(request);
        if (!ipList.contains(ip)) {
            throw new RuntimeException("当前服务不能访问");
        }
    }

}
